package com.yunwaikeji.gy_tool_library.mvvm.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yunwaikeji.gy_tool_library.utils.GYNetExceptionUtils
import com.yunwaikeji.gy_tool_library.mvvm.net.GYStateModel
import com.yunwaikeji.gy_tool_library.mvvm.net.GYStateType
import kotlinx.coroutines.launch

open class GYViewModel : ViewModel() {
    val requestData = MutableLiveData<GYStateModel>()
    val responseData = MutableLiveData<GYStateModel>()

    fun request(block: suspend () -> Unit) {
        viewModelScope.launch {
            runCatching {
                block()
                requestData.value = GYStateModel(GYStateType.SUCCESS, "")
            }.onSuccess {
            }.onFailure {
                if (onFailureResult == null) {
                    val errorResult = GYNetExceptionUtils.getErrorResult(it)
                    requestData.value = GYStateModel(GYStateType.ERROR, errorResult)
                } else {
                    requestData.value =
                        GYStateModel(GYStateType.ERROR, onFailureResult!!.onFailure(it))
                }
            }
        }
    }

    private var onFailureResult: OnFailureResult? = null

    interface OnFailureResult {
        fun onFailure(throwable: Throwable): String
    }

    fun setOnFailureResult(onFailureResult: OnFailureResult) {
        this.onFailureResult = onFailureResult
    }
}